﻿using System.Collections.Generic;
using System.Linq;
using BookShop.DAL;
using BookShop.DTO;
using BookShop.Library.Constant;

namespace BookShop.BLL
{
    public class PublisherService
    {
        public static Publisher Add(Publisher publisher)
        {
            using (var repository = new PublisherRepository())
            {
                var existedPublisher = GetByName(publisher.Name);
                if (existedPublisher != null)
                {
                    return null;
                }
                return repository.Add(publisher);
            }
        }
        public static bool Delete(Publisher publisher)
        {
            using (var repository = new PublisherRepository())
            {
                return repository.Delete(publisher);
            }
        }
        public static List<Publisher> GetAll()
        {
            using (var repository = new PublisherRepository())
            {
                return repository.FindAll(p => p.Status == PublisherStatus.Active).OrderBy(p => p.Name).ToList();
            }
        }
        public static Publisher GetById(int publisherId)
        {
            using (var repository = new PublisherRepository())
            {
                return repository.Find(p => p.Id == publisherId);
            }
        }
        public static Publisher GetByName(string name)
        {
            using (var repository = new PublisherRepository())
            {
                return repository.Find(p => p.Name.Equals(name.Trim().ToLower()));
            }
        }
        public static List<Publisher> Search(int? publisherId, string name, int? status, int page, int pageSize,
            out int count)
        {
            var repository = new PublisherRepository();
            var returnList = new List<Publisher>();
            if (publisherId.HasValue)
            {
                var publisher = GetById(publisherId.Value);
                if (publisher != null)
                {
                    returnList.Add(publisher);
                }
            }
            else
            {
                returnList = repository.GetAll().ToList();
                if (!string.IsNullOrWhiteSpace(name))
                {
                    returnList = returnList.FindAll(p => p.Name.ToLower().Contains(name.Trim().ToLower()));
                }
                if (status.HasValue)
                {
                    returnList = returnList.FindAll(p => p.Status == status.Value);
                }
            }
            count = returnList.Count;
            return returnList.Skip((page - 1) * pageSize).Take(pageSize).ToList();
        }
        public static Publisher Update(Publisher publisher)
        {
            using (var repository = new PublisherRepository())
            {
                return repository.Update(publisher);
            }
        }
    }
}
